<template>
  <div class="game-detail-page">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="container">
        <div class="nav-content">
          <router-link to="/" class="logo">
            <h1>🎮 游戏平台</h1>
          </router-link>
          <div class="nav-menu">
            <router-link to="/" class="nav-item">首页</router-link>
            <router-link to="/games" class="nav-item">游戏列表</router-link>
          </div>
        </div>
      </div>
    </nav>

    <div class="container" v-if="game">
      <!-- 游戏详情 -->
      <div class="game-detail">
        <div class="game-header">
          <div class="game-image">
            <img :src="game.imageUrl" :alt="game.title">
          </div>
          <div class="game-info">
            <h1>{{ game.title }}</h1>
            <p class="game-developer">开发商：{{ game.developer }}</p>
            <p class="game-category">分类：{{ game.category }}</p>
            <p class="game-release-date">发布日期：{{ formatDate(game.releaseDate) }}</p>
            
            <div class="game-rating">
              <div class="rating-stars">
                <el-rate 
                  v-model="game.averageRating" 
                  disabled 
                  show-score 
                  text-color="#ff9900"
                  score-template="平均 {value} 分"
                />
              </div>
              <p class="rating-count">{{ game.ratingCount }} 人评分</p>
            </div>
            
            <div class="game-actions">
              <button class="action-btn like-btn" @click="likeGame">
                <el-icon><thumb-up /></el-icon>
                点赞 ({{ game.likeCount }})
              </button>
              <button class="action-btn favorite-btn" @click="favoriteGame">
                <el-icon><star /></el-icon>
                收藏 ({{ game.favoriteCount }})
              </button>
            </div>
            
            <!-- 评分功能 -->
            <div class="rating-section" v-if="user">
              <h3>为游戏评分</h3>
              <el-rate 
                v-model="userRating" 
                @change="submitRating"
                :max="5"
                show-text
                :texts="['很差', '较差', '一般', '不错', '很好']"
              />
            </div>
          </div>
        </div>
        
        <div class="game-description">
          <h2>游戏描述</h2>
          <p>{{ game.description }}</p>
        </div>
      </div>
      
      <!-- 评论区 -->
      <div class="comments-section">
        <h2>用户评论</h2>
        
        <!-- 发表评论 -->
        <div class="comment-form" v-if="user">
          <el-input 
            v-model="newComment"
            type="textarea"
            placeholder="写下你的评论..."
            :rows="3"
            maxlength="500"
            show-word-limit
          />
          <div class="comment-actions">
            <button class="btn btn-primary" @click="submitComment">发表评论</button>
          </div>
        </div>
        
        <div class="login-prompt" v-else>
          <p>请 <router-link to="/login">登录</router-link> 后发表评论</p>
        </div>
        
        <!-- 评论列表 -->
        <div class="comments-list">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <span class="comment-author">{{ comment.username }}</span>
              <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
            </div>
            <p class="comment-content">{{ comment.content }}</p>
          </div>
          
          <div v-if="comments.length === 0" class="no-comments">
            <p>暂无评论，快来发表第一条评论吧！</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-icon class="loading-icon"><loading /></el-icon>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { gameAPI, commentAPI, ratingAPI } from '../api'

export default {
  name: 'GameDetail',
  setup() {
    const route = useRoute()
    const game = ref(null)
    const comments = ref([])
    const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
    const newComment = ref('')
    const userRating = ref(0)
    const loading = ref(false)
    
    const loadGameDetail = async () => {
      try {
        loading.value = true
        const gameId = route.params.id
        const response = await gameAPI.getGameById(gameId)
        if (response.code === 200) {
          game.value = response.data
        }
      } catch (error) {
        console.error('加载游戏详情失败:', error)
        ElMessage.error('加载游戏详情失败')
      } finally {
        loading.value = false
      }
    }
    
    const loadComments = async () => {
      try {
        const gameId = route.params.id
        const response = await commentAPI.getComments(gameId)
        if (response.code === 200) {
          comments.value = response.data
        }
      } catch (error) {
        console.error('加载评论失败:', error)
      }
    }
    
    const likeGame = async () => {
      try {
        const response = await gameAPI.likeGame(game.value.id)
        if (response.code === 200) {
          ElMessage.success('点赞成功')
          game.value.likeCount += 1
        }
      } catch (error) {
        console.error('点赞失败:', error)
        ElMessage.error('点赞失败')
      }
    }
    
    const favoriteGame = async () => {
      try {
        const response = await gameAPI.favoriteGame(game.value.id)
        if (response.code === 200) {
          ElMessage.success('收藏成功')
          game.value.favoriteCount += 1
        }
      } catch (error) {
        console.error('收藏失败:', error)
        ElMessage.error('收藏失败')
      }
    }
    
    const submitComment = async () => {
      if (!newComment.value.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }
      
      try {
        const response = await commentAPI.createComment({
          gameId: game.value.id,
          userId: user.value.id,
          content: newComment.value
        })
        
        if (response.code === 201) {
          ElMessage.success('评论发表成功')
          newComment.value = ''
          loadComments()
        }
      } catch (error) {
        console.error('发表评论失败:', error)
        ElMessage.error('发表评论失败')
      }
    }
    
    const submitRating = async (value) => {
      if (value === 0) return
      
      try {
        const response = await ratingAPI.createRating({
          gameId: game.value.id,
          userId: user.value.id,
          rating: value
        })
        
        if (response.code === 201) {
          ElMessage.success('评分提交成功')
          loadGameDetail() // 重新加载游戏详情以更新评分
        } else if (response.message && response.message.includes('已评分')) {
          ElMessage.success('评分更新成功')
          loadGameDetail()
        }
      } catch (error) {
        console.error('评分失败:', error)
        ElMessage.error('评分提交失败')
      }
    }
    
    const formatDate = (date) => {
      if (!date) return '未知'
      return new Date(date).toLocaleDateString('zh-CN')
    }
    
    onMounted(() => {
      loadGameDetail()
      loadComments()
    })
    
    return {
      game,
      comments,
      user,
      newComment,
      userRating,
      loading,
      likeGame,
      favoriteGame,
      submitComment,
      submitRating,
      formatDate
    }
  }
}
</script>

<style scoped>
.game-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 导航栏样式 */
.navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 1rem 0;
}

.nav-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  text-decoration: none;
}

.logo h1 {
  color: white;
  font-size: 1.8rem;
  font-weight: bold;
}

.nav-menu {
  display: flex;
  gap: 2rem;
}

.nav-item {
  color: white;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.nav-item:hover {
  color: #f0f0f0;
}

/* 游戏详情 */
.game-detail {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin: 2rem 0;
}

.game-header {
  display: flex;
  gap: 2rem;
  padding: 2rem;
}

.game-image {
  flex: 0 0 300px;
  height: 400px;
  border-radius: 8px;
  overflow: hidden;
}

.game-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.game-info {
  flex: 1;
}

.game-info h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 1rem;
}

.game-developer,
.game-category,
.game-release-date {
  color: #666;
  margin-bottom: 0.5rem;
  font-size: 1.1rem;
}

.game-rating {
  margin: 1.5rem 0;
}

.rating-count {
  color: #666;
  font-size: 0.9rem;
  margin-top: 0.5rem;
}

.game-actions {
  display: flex;
  gap: 1rem;
  margin: 1.5rem 0;
}

.action-btn {
  padding: 0.8rem 1.5rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.3s ease;
}

.like-btn {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.favorite-btn {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  color: #333;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.rating-section {
  margin-top: 2rem;
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.rating-section h3 {
  margin-bottom: 1rem;
  color: #333;
}

.game-description {
  padding: 2rem;
  border-top: 1px solid #e0e0e0;
}

.game-description h2 {
  color: #333;
  margin-bottom: 1rem;
}

.game-description p {
  color: #666;
  line-height: 1.6;
  font-size: 1.1rem;
}

/* 评论区 */
.comments-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  margin: 2rem 0;
}

.comments-section h2 {
  color: #333;
  margin-bottom: 1.5rem;
}

.comment-form {
  margin-bottom: 2rem;
}

.comment-actions {
  margin-top: 1rem;
  text-align: right;
}

.login-prompt {
  text-align: center;
  padding: 2rem;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 2rem;
}

.login-prompt a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.comment-item {
  border-bottom: 1px solid #e0e0e0;
  padding: 1.5rem 0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.comment-author {
  font-weight: 500;
  color: #333;
}

.comment-time {
  color: #666;
  font-size: 0.9rem;
}

.comment-content {
  color: #666;
  line-height: 1.6;
}

.no-comments {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  color: #666;
}

.loading-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-content {
    flex-direction: column;
    gap: 1rem;
  }
  
  .game-header {
    flex-direction: column;
    padding: 1rem;
  }
  
  .game-image {
    flex: none;
    height: 250px;
  }
  
  .game-info h1 {
    font-size: 2rem;
  }
  
  .game-actions {
    flex-direction: column;
  }
  
  .action-btn {
    justify-content: center;
  }
}
</style>